package com.bj58.groupbuy.action.controllers;

import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.web.bind.ServletRequestUtils;

import com.bj58.groupbuy.action.model.AdDataRecord;
import com.bj58.groupbuy.action.model.AdMetricsDay;
import com.bj58.groupbuy.action.model.AllianceBillingMetrics;
import com.bj58.groupbuy.action.model.ZSClickInfo;
import com.bj58.groupbuy.action.service.AdDataRecordService;
import com.bj58.groupbuy.action.service.AdMetricsDayService;
import com.bj58.groupbuy.action.service.DataWebIFService;
import com.bj58.groupbuy.action.service.MostService;
import com.bj58.groupbuy.action.util.DateUtil;
import com.bj58.groupbuy.cache.MemCacheTool;
import com.bj58.groupbuy.service.locator.ServiceLocator;
import com.bj58.groupbuy.util.IOUtils;
import com.bj58.wf.mvc.ActionResult;
import com.bj58.wf.mvc.BeatContext.Model;
import com.bj58.wf.mvc.MvcController;
import com.bj58.wf.mvc.actionresult.ContentResult;
import com.bj58.wf.mvc.annotation.GET;
import com.bj58.wf.mvc.annotation.POST;
import com.bj58.wf.mvc.annotation.Path;

@Path("most")
public class MostController   extends MvcController{
	
	private	MostService service = ServiceLocator.get(MostService.class);
	private	AdDataRecordService adDataRecordService = ServiceLocator.get(AdDataRecordService.class);
	private	AdMetricsDayService adMetricsDayService = ServiceLocator.get(AdMetricsDayService.class);
	private DataWebIFService dataWebIFService = ServiceLocator.get(DataWebIFService.class);
	
	private static final String lackPar = "LackParameter";
	private static final String error = "Error";
	private static final String noData = "NoData";
	
	@Path("follows")
	@POST
	@GET
	public ActionResult follows () throws Exception{
		HttpServletRequest request = beat.getRequest();
		Model model= beat.getModel();
		
		String key = "mostfollows_cityid_%d";
		String reval = "";
		try{
			int cityid = ServletRequestUtils.getIntParameter(request, "cityid", 0);
			int num = ServletRequestUtils.getIntParameter(request, "num", 0);
			
			if(cityid == 0){
				cityid = 2;
			}
			
			if(num == 0){
				num = 9;
			}
			
			key = String.format(key, cityid);
			
			List<Long> list = service.getMostFollows(cityid, num);
			int rec = list.size();
			int k = 0;
			for(long gbid : list){
				k++;
				reval += String.valueOf(gbid);
				if(k < rec ){
					reval+= ",";
				}
			}
			
			MemCacheTool.setValue(key,reval,100); //缓存100分钟
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		model.add("output",reval);
		return ActionResult.view("most/follows");
	}
	
	@Path("cachefollows")
	@POST
	@GET
	public ActionResult cachefollows() throws Exception{
		HttpServletRequest request = beat.getRequest();
		String reval = "";
		int cityid = ServletRequestUtils.getIntParameter(request, "cityid", 0);
		String key = "mostfollows_cityid_%d";
		
		if(cityid == 0){
			cityid = 2;
		}
		
		key = String.format(key, cityid);
		reval =String.valueOf( MemCacheTool.getValue(key) );
		beat.getModel().add("output",reval);
		return ActionResult.view("most/cachefollows");
	}
	
	
	/**广告渠道数据接口-查询单渠道时间段订单及销售数据
	 * @param utmsource   渠道名
	 * @param campaign   活动名
	 * @param starttime 起始时间
	 * @param endtime  结束时间 
	 * @return  销售额 = pa   订单数 = oc  日期  date
	 * @throws Exception 
	 */
	@Path("addata")
	@POST
	@GET
	public ActionResult adddata (){
		HttpServletRequest request = beat.getRequest();
		HttpServletResponse response = beat.getResponse();
		try{
			String utmsource = ServletRequestUtils.getStringParameter(request, "utmsource","");
			String campaign = ServletRequestUtils.getStringParameter(request, "campaign","");
			String starttime = ServletRequestUtils.getStringParameter(request, "starttime","");
			String endtime = ServletRequestUtils.getStringParameter(request, "endtime","");
			
			if("".equals(utmsource) || "".equals(starttime) || "".equals(endtime) ){
				return new ContentResult("lackparam");
			}
			//查询订单和销售额数据返回
			String con = "visit_date>='"+starttime+"'";
			con = con+"&visit_date<='"+endtime+"'";
			con = con+"&ad='"+utmsource+"'";
			if(!"".equals(campaign) &&  !"null".equals(campaign) &&  !"NULL".equals(campaign)){
				con = con+"&campaign='"+campaign+"'";
			}
			String cols = "visit_date,order_count,pay_order_amount";
			List<AdMetricsDay> rsList = adMetricsDayService.getAdData(cols, con);
			if(null == rsList || rsList.isEmpty() ){
				return new ContentResult("nodata");
			}
			String result ="";
			for(AdMetricsDay vo : rsList){
				int oc = vo.getOrder_count();
				double pa =vo.getPay_order_amount();
				String date = vo.getVisit_date();
				result = result+"date="+date+"&oc="+oc+"&pa="+pa+"||";
			}
			result = result.substring(0,result.lastIndexOf("||"));
			response.setContentType("text/plain; charset=utf-8");
			PrintWriter pw = response.getWriter();
			pw.write(result);
			response.flushBuffer();
			IOUtils.closeQuietly(pw);
			
		}catch (Exception e) {
			e.printStackTrace();
			return new ContentResult("error");
		}
		return null;
	}
	
	/**广告渠道数据接口-花费数据插入记录
	 * 
	 * @param utmsource   渠道名
	 * @param starttime 起始时间
	 * @param endtime  结束时间 
	 * @param cost  广告花费
	 * @throws Exception 
	 */
	@Path("adcost")
	@POST
	@GET
	public ActionResult adcost (){
		HttpServletRequest request = beat.getRequest();
		try{
			String utmsource = ServletRequestUtils.getStringParameter(request, "utmsource","");
			double cost = ServletRequestUtils.getDoubleParameter(request, "cost", 0);
			String starttime = ServletRequestUtils.getStringParameter(request, "starttime","");
			String endtime = ServletRequestUtils.getStringParameter(request, "endtime","");
			
			if("".equals(utmsource) || "".equals(starttime) || "".equals(endtime)){
				return new ContentResult("lackparam");
			}
			//插入渠道日消费数据
			AdDataRecord  adr = new AdDataRecord();
			adr.setUtmsource(utmsource);
			adr.setCost(cost);
			adr.setStarttime(starttime);
			adr.setEndtime(endtime);
			adr.setStatdate(DateUtil.getStringDate(new Date(), "yyyy-MM-dd"));
			int id = (Integer)adDataRecordService.save(adr);
			System.out.println(id);
		}catch (Exception e) {
			e.printStackTrace();
			return new ContentResult("error");
		}
		return new ContentResult("success");
	}
	
	
	/**联盟品类数据接口
	 * 参数  beginDate  endDate  起始日期  格式 ：yyyy-MM-dd
	 * @return
	 */
	@Path("allianceCate")
	@POST
	@GET
	public ActionResult allianceCate (){
		HttpServletRequest request = beat.getRequest();
		HttpServletResponse response = beat.getResponse();		
		String result = "";
		try{
			
			String beginDate = ServletRequestUtils.getStringParameter(request, "beginDate","");
			String endDate = ServletRequestUtils.getStringParameter(request, "endDate","");
			if("".equals(beginDate) || "".equals(endDate)){
				result = lackPar;
			}else{
				List<AllianceBillingMetrics> rsList = dataWebIFService.getAllianceCate(beginDate, endDate);
				if(null == rsList || rsList.isEmpty()){
					result = noData;
				}else{
					TreeMap<String,List<AllianceBillingMetrics>>  abmMap = new TreeMap<String,List<AllianceBillingMetrics>>();
					for(AllianceBillingMetrics vo : rsList){
						List<AllianceBillingMetrics> tempList = new ArrayList<AllianceBillingMetrics>();
						String statDate = vo.getStatDate();
						if(abmMap.containsKey(statDate)){
							tempList = abmMap.get(statDate);
						}
						tempList.add(vo);
						abmMap.put(statDate, tempList);
					}
					
					DecimalFormat  df = new DecimalFormat("0.00");
					JSONObject json = new JSONObject();
					for(Iterator<String> it =  abmMap.keySet().iterator(); it.hasNext();){
						String date = it.next();
						List<AllianceBillingMetrics> tempList = abmMap.get(date);
						Map<String,String> tempMap = new HashMap<String,String>();
						for(AllianceBillingMetrics vo : tempList){
							tempMap.put(vo.getCate1(),df.format(vo.getAmount()));
						}
						json.accumulate(date, tempMap);
					}
					response.setContentType("text/plain; charset=utf-8");
					PrintWriter pw = response.getWriter();
					pw.write(json.toString());
					response.flushBuffer();
					IOUtils.closeQuietly(pw);
				}
			}
		}catch (Exception e) {
			result = error;
			e.printStackTrace();
		}
		return new ContentResult(result);
		
	} 
	
	
	
	/**招商加盟合作商点击数据接口
	 * 参数  beginDate  endDate  起始日期  格式 ：yyyy-MM-dd
	 * @return
	 */
	@Path("zsclickinfo")
	@POST
	@GET
	public ActionResult zsClickInfo (){
		HttpServletRequest request = beat.getRequest();
		HttpServletResponse response = beat.getResponse();		
		String result = "";
		try{
			String beginDate = ServletRequestUtils.getStringParameter(request, "beginDate","");
			String endDate = ServletRequestUtils.getStringParameter(request, "endDate","");
			if("".equals(beginDate) || "".equals(endDate)){
				result = lackPar;
			}else{
				List<ZSClickInfo> rsList = dataWebIFService.getZSclickinfo(beginDate, endDate);
				if(null == rsList || rsList.isEmpty()){
					result = noData;
				}else{
					TreeMap<String,List<ZSClickInfo>>  abmMap = new TreeMap<String,List<ZSClickInfo>>();
					for(ZSClickInfo vo : rsList){
						List<ZSClickInfo> tempList = new ArrayList<ZSClickInfo>();
						String statDate = vo.getStat_date();
						String key  = statDate +"_" + vo.getPay_order_count();
						if(abmMap.containsKey(key)){
							tempList = abmMap.get(key);
						}
						tempList.add(vo);
						abmMap.put(key, tempList);
					}
					
					JSONObject json = new JSONObject();
					for(Iterator<String> it =  abmMap.keySet().iterator(); it.hasNext();){
						String date = it.next();
						List<ZSClickInfo> tempList = abmMap.get(date);
						Map<String,Integer> tempMap = new HashMap<String,Integer>();
						for(ZSClickInfo vo : tempList){
							tempMap.put(vo.getLottery_name(),vo.getOrder_count());
						}
						json.accumulate(date, tempMap);
					}
					response.setContentType("text/plain; charset=utf-8");
					PrintWriter pw = response.getWriter();
					pw.write(json.toString());
					response.flushBuffer();
					IOUtils.closeQuietly(pw);
				}
			}
		}catch (Exception e) {
			result = error;
			e.printStackTrace();
		}
		return new ContentResult(result);
		
	} 
}
